<template>
  <el-drawer
    v-model="dialogVisible"
    :title="dialogTitle"
    :direction="'rtl'"
    :size="'80%'"
    :close-on-click-modal="false"
    :before-close="handleClose"
    class="optimized-party-selector"
    destroy-on-close
  >
    <div class="dialog-content" style="height: 100%; min-height: 0">
      <!-- 标签页导航 -->
      <el-tabs v-model="activeTab" class="party-tabs" @tab-change="handleTabChange">
        <!-- 客户及联系人选项卡 -->
        <el-tab-pane label="客户及联系人" name="customer">
          <div class="tab-content scrollable-tab-content customer-contacts-section">
            <el-alert
              title="从当前合同的客户及其联系人中选择当事人"
              type="info"
              :closable="false"
              show-icon
              class="tab-alert"
            />

            <div class="party-options">
              <!-- 客户本身 -->
              <div
                class="party-option customer-option"
                :class="{ selected: selectedParty && selectedParty.party_source === 1 }"
                @click="selectCustomerAsParty"
              >
                <div class="party-info">
                  <div class="party-name">{{ localContractInfo?.customer }}</div>
                  <div class="party-type">客户本身</div>
                </div>
                <div class="party-meta">
                  <el-tag type="primary">客户</el-tag>
                </div>
              </div>

              <!-- 客户联系人列表 -->
              <div class="contact-list">
                <div class="list-header">
                  <h5>客户联系人</h5>
                  <el-input
                    v-model="searchKeyword"
                    placeholder="搜索联系人姓名或电话"
                    clearable
                    @clear="handleClear"
                    @keyup.enter="handleSearch"
                    class="search-input"
                  >
                    <template #append>
                      <el-button @click="handleSearch" :loading="loading">
                        <el-icon><Search /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                </div>
                <div v-if="loading && activeTab === 'customer'" class="loading-container">
                  <el-skeleton :rows="3" animated />
                </div>
                <div v-else-if="customerContacts.length === 0" class="no-contacts">
                  <el-empty description="暂无联系人信息" />
                </div>
                <div
                  v-for="contact in customerContacts"
                  :key="contact.id"
                  class="party-option contact-option"
                  :class="{ selected: selectedParty && selectedParty.contact_id === contact.id }"
                  @click="selectContactAsParty(contact)"
                >
                  <div class="party-info">
                    <div class="party-name">{{ contact.name }}</div>
                    <div class="party-phone" v-if="contact.mobile">电话：{{ contact.mobile }}</div>
                  </div>
                  <div class="party-meta">
                    <el-tag type="success">联系人</el-tag>
                  </div>
                </div>

                <!-- 分页组件 -->
                <div v-if="!loading && customerContacts.length > 0" class="pagination-container">
                  <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalContacts"
                    @size-change="handlePageSizeChange"
                    @current-change="handlePageChange"
                  />
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 外部当事人选项卡 -->
        <el-tab-pane label="外部当事人" name="external">
          <div class="tab-content scrollable-tab-content external-parties-section">
            <el-alert
              title="选择或添加外部当事人"
              type="info"
              :closable="false"
              show-icon
              class="tab-alert"
            />

            <div class="external-party-section">
              <!-- 已有的外部当事人列表 -->
              <div class="external-parties-section">
                <div class="list-header">
                  <div class="header-left">
                    <el-input
                      v-model="externalSearchKeyword"
                      placeholder="搜索当事人名称或手机号"
                      prefix-icon="el-icon-search"
                      clearable
                      @clear="handleExternalSearch"
                      @input="handleExternalSearch"
                      class="search-input"
                    />
                  </div>
                  <el-button type="primary" @click="prepareAddNewParty">添加新外部当事人</el-button>
                </div>

                <div v-if="loading && activeTab === 'external'" class="loading-container">
                  <el-skeleton :rows="3" animated />
                </div>

                <div v-else-if="externalParties.length > 0" class="party-options">
                  <div
                    v-for="party in externalParties"
                    :key="party.id"
                    class="party-option external-option"
                    :class="{ selected: selectedParty && selectedParty.id === party.id }"
                    @click="selectExternalParty(party)"
                  >
                    <div class="party-info">
                      <div class="party-name">{{ party.name }}</div>
                      <div class="party-type">
                        {{ party.party_type === 1 ? '个人' : '企业' }}
                        <span v-if="party.id_number">（{{ party.id_number }}）</span>
                      </div>
                      <div v-if="party.phone" class="party-phone">电话：{{ party.phone }}</div>
                    </div>
                    <div class="party-meta">
                      <el-tag type="warning">外部</el-tag>
                    </div>
                  </div>
                </div>

                <div v-else class="no-contacts">
                  <el-empty description="暂无外部当事人，点击添加按钮创建" />
                </div>

                <!-- 分页组件 -->
                <div v-if="totalExternalParties > 0" class="pagination-container">
                  <el-pagination
                    v-model:current-page="externalCurrentPage"
                    v-model:page-size="externalPageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalExternalParties"
                    @size-change="handleExternalSizeChange"
                    @current-change="handleExternalCurrentChange"
                  />
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 当事人通用表单 -->
      <div class="party-detail-section">
        <el-divider content-position="left">
          {{ isAddingNewParty ? '新增外部当事人' : '当事人详细信息' }}
        </el-divider>

        <template v-if="selectedParty || isAddingNewParty">
          <el-form
            ref="partyDetailFormRef"
            :model="partyDetailForm"
            :rules="partyDetailRules"
            label-width="120px"
            class="party-detail-form-content"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="当事人名称" prop="name">
                  <el-input
                    v-model="partyDetailForm.name"
                    :disabled="!isAddingNewParty && selectedParty === null"
                    placeholder="请输入当事人名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="当事人类型" prop="party_type">
                  <el-select
                    v-model="partyDetailForm.party_type"
                    :disabled="!isAddingNewParty && selectedParty === null"
                    placeholder="请选择类型"
                  >
                    <el-option :value="1" label="个人" />
                    <el-option :value="2" label="企业" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="委托身份" prop="is_client">
                  <el-select v-model="partyDetailForm.is_client" placeholder="请选择委托身份">
                    <el-option :value="1" label="委托人" />
                    <el-option :value="2" label="对方当事人" />
                    <el-option :value="3" label="第三人" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="诉讼地位" prop="relationship">
                  <el-select v-model="partyDetailForm.relationship" placeholder="请选择诉讼地位">
                    <el-option :value="0" label="未知" />
                    <el-option :value="1" label="原告" />
                    <el-option :value="2" label="被告" />
                    <el-option :value="3" label="第三人" />
                    <el-option :value="4" label="上诉人" />
                    <el-option :value="5" label="被上诉人" />
                    <el-option :value="6" label="再审申请人" />
                    <el-option :value="7" label="再审被申请人" />
                    <el-option :value="8" label="申请执行人" />
                    <el-option :value="9" label="被申请执行人" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="证件号码" prop="id_number">
                  <el-input
                    v-model="partyDetailForm.id_number"
                    :disabled="!isAddingNewParty && selectedParty === null"
                    placeholder="请输入证件号码"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人" prop="contact">
                  <el-input
                    v-model="partyDetailForm.contact"
                    :disabled="!isAddingNewParty && selectedParty === null"
                    placeholder="请输入联系人"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input
                    v-model="partyDetailForm.phone"
                    :disabled="!isAddingNewParty && selectedParty === null"
                    placeholder="请输入联系电话"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="地址" prop="address">
                  <el-input
                    v-model="partyDetailForm.address"
                    :disabled="!isAddingNewParty && selectedParty === null"
                    placeholder="请输入地址"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button
                @click="
                  () => {
                    isAddingNewParty = false
                    selectedParty = null
                  }
                "
                v-if="isAddingNewParty"
              >
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </template>

        <!-- 当没有选中当事人时的提示 -->
        <template v-else>
          <div class="no-party-selected">
            <el-alert title="请从上方选择一个当事人" type="info" :closable="false" show-icon />
          </div>
        </template>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" :disabled="loading">取消</el-button>
        <el-button
          type="primary"
          @click="confirmSelection"
          :loading="loading"
          :disabled="!canConfirm"
        >
          确认添加
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import request from '@/utils/request'
  import { isValidId, isValidPositiveId, getValidContractId } from '@/utils/contractUtils'

  // 定义接口
  interface ContractInfo {
    id: number
    code: string
    name: string
    customer_id: number
    customer: string
    // 其他合同字段...
  }

  interface CustomerContact {
    id: number
    name: string
    mobile: string
    // 其他联系人字段...
  }

  interface Party {
    id: number
    name: string
    party_type: number
    party_source: number
    contract_id: number
    contact_id: number
    id_number: string
    phone: string
    contact: string
    address: string
    // 其他当事人字段...
  }

  // Props和Emits
  const props = defineProps<{
    modelValue: boolean
    caseId?: number
    contractId?: number
    // 可选的合同信息，避免重复请求
    contractInfo?: ContractInfo | null
    // 可选的联系人列表，避免重复请求
    contactList?: CustomerContact[]
  }>()

  const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    success: []
  }>()

  // 响应式数据
  const activeTab = ref('customer')
  const loading = ref(false)
  const isAddingNewParty = ref(false)

  // 合同和当事人信息
  const localContractInfo = ref<ContractInfo | null>(null)
  const customerContacts = ref<CustomerContact[]>([])
  const externalParties = ref<Party[]>([])

  // 分页和搜索相关数据
  // 联系人搜索和分页
  const searchKeyword = ref('')
  const currentPage = ref(1)
  const pageSize = ref(10)
  const totalContacts = ref(0)

  // 外部当事人搜索和分页
  const externalSearchKeyword = ref('')
  const externalCurrentPage = ref(1)
  const externalPageSize = ref(10)
  const totalExternalParties = ref(0)

  // 选中的当事人
  const selectedParty = ref<Party | null>(null)

  // 表单引用
  const partyDetailFormRef = ref<FormInstance>()

  // 统一的当事人表单
  const partyDetailForm = reactive({
    name: '',
    party_type: 1, // 确保必填字段有默认值
    id_number: '', // 非必填字段
    phone: '',
    contact: '',
    address: '',
    is_client: 1, // 确保必填字段有默认值
    relationship: 1, // 确保必填字段有默认值
  })

  // 统一的表单验证规则
  const partyDetailRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入当事人名称', trigger: 'blur' }],
    party_type: [{ required: true, message: '请选择当事人类型', trigger: 'change' }],
    id_number: [{ required: false, message: '请输入证件号码', trigger: 'blur' }],
    is_client: [{ required: true, message: '请选择委托身份', trigger: 'change' }],
    relationship: [{ required: true, message: '请选择诉讼地位', trigger: 'change' }],
    phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  })

  // 计算属性
  const dialogVisible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const dialogTitle = computed(() => {
    return props.contractId ? `案件当事人管理 - 合同关联` : `案件当事人管理`
  })

  const canConfirm = computed(() => {
    // 支持两种场景：选中现有当事人或处于新增模式且表单有必要信息
    // 修改为：id_number改为非必填，移除is_client和relationship的强制要求
    return (
      (selectedParty.value !== null && !isAddingNewParty.value) ||
      (isAddingNewParty.value &&
        partyDetailForm.name &&
        partyDetailForm.party_type !== undefined &&
        partyDetailForm.is_client !== undefined &&
        partyDetailForm.relationship !== undefined)
    )
  })

  // 监听selectedParty的变化
  watch(
    selectedParty,
    newVal => {
      if (newVal) {
        // 重置表单验证状态
        if (partyDetailFormRef.value) {
          partyDetailFormRef.value.clearValidate()
        }
        // 自动填充完整的表单数据
        Object.assign(partyDetailForm, {
          name: newVal.name || '',
          party_type: newVal.party_type || 1,
          id_number: newVal.id_number || '',
          contact: newVal.contact || '',
          phone: newVal.phone || '',
          address: newVal.address || '',
          is_client: 1,
          relationship: 1,
        })
        // 切换到查看详情模式
        isAddingNewParty.value = false
      } else if (!isAddingNewParty.value) {
        // 清空表单
        Object.assign(partyDetailForm, {
          name: '',
          party_type: 1,
          id_number: '',
          phone: '',
          contact: '',
          address: '',
          is_client: 1,
          relationship: 1,
        })
      }
    },
    { deep: true }
  )

  // 已在contractUtils.ts中定义，这里不再重复定义
  // isValidId, isValidContractId和isValidCaseId已从contractUtils.ts导入

  // 方法定义
  const loadContractInfo = async () => {
    // 检查合同ID是否存在且不为空字符串，允许合同ID为0的情况
    if (
      props.contractId === null ||
      props.contractId === undefined ||
      String(props.contractId).trim() === ''
    ) {
      return
    }

    try {
      loading.value = true
      const response: any = await request.get(`/api/contract/contract/view?id=${props.contractId}`)
      if (response.code === 0) {
        localContractInfo.value = response.data
        // 调用loadCustomerContacts加载客户联系人
        await loadCustomerContacts()

        // 使用一致的合同ID检查逻辑
        if (
          props.contractId !== null &&
          props.contractId !== undefined &&
          String(props.contractId).trim() !== ''
        ) {
          await loadExternalParties()
        }
      } else {
        // 避免显示"合同ID不存在"等错误提示，因为这可能是正常情况
        if (
          !response.msg ||
          (!response.msg.includes('合同ID不存在') && !response.msg.includes('合同不存在'))
        ) {
          ElMessage.error(response.msg || '获取合同信息失败')
        }
      }
    } catch (error) {
      // 对于合同相关的异常，避免显示通用错误提示，因为这可能是正常情况
      // 只有在控制台记录错误，不向用户显示
    } finally {
      loading.value = false
    }
  }

  const loadCustomerContacts = async () => {
    // 检查localContractInfo是否存在
    if (!localContractInfo.value) {
      return
    }

    // 只使用标准的customer_id字段名
    const customerId = localContractInfo.value.customer_id
    if (!customerId || !isValidId(customerId)) {
      return
    }

    try {
      loading.value = true
      // 添加分页和搜索参数，确保参数直接传递
      const customer_id = customerId
      const page = currentPage.value
      const limit = pageSize.value
      const keywords = searchKeyword.value.trim()
      // 构建请求参数对象，确保参数名称与后端一致
      const requestParams: { customer_id: number; page: number; limit: number; keywords?: string } =
        {
          customer_id,
          page,
          limit,
        }

      // 只有当关键词不为空时才添加到请求参数中
      if (keywords) {
        requestParams.keywords = keywords
      }

      // 直接传递参数对象，避免params嵌套，使用类型断言解决TypeScript类型错误
      const response: any = await request.get('/api/customer/contact/list', requestParams as any)
      if (response.code === 0) {
        let contacts = response.data || []
        let total = 0
        // 处理可能的数据结构差异
        if (Array.isArray(contacts.list)) {
          contacts = contacts.list
          total = response.data.total || 0
        } else {
          // 如果返回的是数组，则总条数为数组长度
          if (Array.isArray(contacts)) {
            total = contacts.length
          } else {
          }
        }

        // 去重处理：根据联系人ID进行去重
        const uniqueContacts = contacts.reduce(
          (acc: CustomerContact[], contact: CustomerContact) => {
            // 检查是否已存在相同ID的联系人
            const existingContact = acc.find(item => item.id === contact.id)
            if (!existingContact) {
              acc.push(contact)
            }
            return acc
          },
          []
        )

        customerContacts.value = uniqueContacts
        totalContacts.value = total
      } else {
        ElMessage.error(response.msg || '获取客户联系人失败')
        customerContacts.value = []
        totalContacts.value = 0
      }
    } catch (error) {
      ElMessage.error('获取客户联系人失败')
      customerContacts.value = []
      totalContacts.value = 0
    } finally {
      loading.value = false
    }
  }

  // 处理搜索
  const handleSearch = async () => {
    const keyword = searchKeyword.value.trim()
    currentPage.value = 1 // 搜索时重置到第一页

    // 直接执行搜索，确保使用最新的搜索关键词
    if (localContractInfo.value && localContractInfo.value.customer_id) {
      await loadCustomerContacts()
    } else {
    }
  }

  // 处理搜索框清除
  const handleClear = () => {
    searchKeyword.value = ''
    handleSearch()
  }

  // 处理分页变化
  const handlePageChange = (newPage: number) => {
    currentPage.value = newPage
    loadCustomerContacts()
  }

  // 处理每页条数变化
  const handlePageSizeChange = (newSize: number) => {
    pageSize.value = newSize
    currentPage.value = 1 // 重置到第一页
    loadCustomerContacts()
  }

  const loadExternalParties = async () => {
    try {
      loading.value = true
      // 获取外部当事人数据，支持搜索和分页
      // 构建请求参数对象，与客户及联系人tab的搜索处理方式保持一致
      const keywords = externalSearchKeyword.value.trim()
      const page = externalCurrentPage.value
      const limit = externalPageSize.value

      // 构建请求参数对象，确保参数名称与后端一致
      const requestParams: { keywords?: string; page: number; limit: number } = {
        page,
        limit,
      }

      // 只有当关键词不为空时才添加到请求参数中
      if (keywords) {
        requestParams.keywords = keywords
      }

      // 直接传递参数对象，避免params嵌套，与客户联系人搜索处理方式保持一致
      const response: any = await request.get('/api/lawcase/parties/list', requestParams as any)
      if (response.code === 0 && response.data) {
        // 转换字段名以匹配模板中使用的字段名
        externalParties.value = response.data.list.map((party: any) => ({
          id: party.id,
          name: party.partyName, // API返回partyName，模板使用name
          party_type: party.partyType, // API返回partyType，模板使用party_type
          id_number: party.idNumber || '', // API返回idNumber，模板使用id_number
          phone: party.phone || '', // 保持字段名一致
          party_source: party.partySource, // 保留原始字段用于其他逻辑
        }))
        // 更新总数
        totalExternalParties.value = response.data.total || 0
      } else {
        ElMessage.error(response.msg || '获取当事人列表失败')
        externalParties.value = []
        totalExternalParties.value = 0
      }
    } catch (error) {
      ElMessage.error('获取当事人列表失败')
      externalParties.value = []
      totalExternalParties.value = 0
    } finally {
      loading.value = false
    }
  }

  // 处理外部当事人搜索
  const handleExternalSearch = () => {
    externalCurrentPage.value = 1 // 重置到第一页
    loadExternalParties()
  }

  // 处理外部当事人每页条数变化
  const handleExternalSizeChange = (size: number) => {
    externalPageSize.value = size
    loadExternalParties()
  }

  // 处理外部当事人当前页变化
  const handleExternalCurrentChange = (current: number) => {
    externalCurrentPage.value = current
    loadExternalParties()
  }

  const selectCustomerAsParty = () => {
    if (!localContractInfo.value) return

    selectedParty.value = {
      id: 0,
      name: localContractInfo.value.customer,
      party_type: 2, // 企业
      party_source: 1, // 客户本身
      contract_id: localContractInfo.value.id,
      contact_id: 0,
      id_number: '',
      phone: '',
      contact: '',
      address: '',
    }

    // 设置默认的当事人详细信息
    Object.assign(partyDetailForm, {
      name: '',
      party_type: 1, // 默认为个人
      is_client: 1, // 默认为委托人
      relationship: 1, // 默认为原告
      id_number: '',
      contact: '',
      phone: '',
      address: '',
      remark: '',
    })

    // 使用nextTick确保DOM更新后再验证表单
    setTimeout(() => {
      if (partyDetailFormRef.value) {
        partyDetailFormRef.value.clearValidate()
      }
    }, 0)
  }

  const selectContactAsParty = (contact: CustomerContact) => {
    if (!localContractInfo.value) return

    selectedParty.value = {
      id: 0,
      name: contact.name,
      party_type: 1, // 个人
      party_source: 2, // 客户联系人
      contract_id: localContractInfo.value.id,
      contact_id: contact.id,
      id_number: '',
      phone: contact.mobile || '',
      contact: contact.name,
      address: '',
    }

    // 设置默认的当事人详细信息
    Object.assign(partyDetailForm, {
      name: contact.name,
      party_type: 1, // 个人
      is_client: 2, // 默认为对方当事人
      relationship: 2, // 默认为被告
      id_number: '',
      contact: contact.name,
      phone: contact.mobile || '',
      address: '',
      remark: '',
    })

    // 使用nextTick确保DOM更新后再验证表单
    setTimeout(() => {
      if (partyDetailFormRef.value) {
        partyDetailFormRef.value.clearValidate()
      }
    }, 0)
  }

  const selectExternalParty = (party: Party) => {
    selectedParty.value = { ...party }

    // 使用nextTick确保DOM更新后再验证表单
    setTimeout(() => {
      if (partyDetailFormRef.value) {
        partyDetailFormRef.value.clearValidate()
      }
    }, 0)
  }

  // 准备添加新外部当事人
  const prepareAddNewParty = () => {
    // 检查合同ID是否存在且不为空字符串，允许合同ID为0的情况
    const hasContractId =
      props.contractId !== null &&
      props.contractId !== undefined &&
      String(props.contractId).trim() !== ''
    if (!hasContractId) {
      ElMessage.warning('请先关联合同')
      return
    }

    // 设置为新增模式
    isAddingNewParty.value = true

    // 清空选中的当事人
    selectedParty.value = null

    // 重置表单数据
    if (partyDetailFormRef.value) {
      partyDetailFormRef.value.resetFields()
    }

    // 初始化表单，统一数据类型
    Object.assign(partyDetailForm, {
      name: '',
      party_type: 1,
      id_number: '',
      phone: '',
      contact: '',
      address: '',
      is_client: 1,
      relationship: 1,
    })

    // 清除表单验证状态
    setTimeout(() => {
      if (partyDetailFormRef.value) {
        partyDetailFormRef.value.clearValidate()
      }
    }, 0)
  }

  const confirmSelection = async () => {
    // 使用isValidId验证案件ID，使用isValidPositiveId确保是正数
    if (!partyDetailFormRef.value || !isValidPositiveId(props.caseId)) return

    // 验证合同ID，允许为0但不能为空
    const fallbackContractId = props.contractId

    if (
      !(
        fallbackContractId !== null &&
        fallbackContractId !== undefined &&
        String(fallbackContractId).trim() !== ''
      )
    ) {
      ElMessage.warning('请先关联合同')
      return
    }

    await partyDetailFormRef.value.validate(async valid => {
      if (valid) {
        try {
          loading.value = true

          if (isAddingNewParty.value) {
            // 新增当事人场景：后端接口已设计为同时处理创建当事人和建立案件关联
            const partyData = {
              ...partyDetailForm,
              party_source: 3, // 外部人员
              contract_id: props.contractId,
              case_id: props.caseId,
              party_name: partyDetailForm.name, // 添加party_name字段，与后端字段保持一致
            }

            // 保存新当事人并建立案件关联
            const partyResponse: any = await request.post('/api/lawcase/parties/add', partyData)
            if (partyResponse.code === 0) {
              ElMessage.success('添加外部当事人并关联案件成功')
              emit('success')
              handleClose()
            } else {
              ElMessage.error(partyResponse.msg || '添加外部当事人失败')
            }
          } else if (selectedParty.value) {
            // 已有当事人场景：直接绑定关系
            const partyContractId = selectedParty.value!.contract_id
            const contractId =
              partyContractId !== null &&
              partyContractId !== undefined &&
              String(partyContractId).trim() !== ''
                ? partyContractId
                : fallbackContractId

            // 直接构造参数对象，避免参数转换问题
            const params = {
              case_id: props.caseId,
              party_id: selectedParty.value!.id || undefined,
              party_name: selectedParty.value!.name,
              party_type: selectedParty.value!.party_type,
              party_source: selectedParty.value!.party_source,
              contract_id: contractId,
              contact_id: selectedParty.value!.contact_id,
              // 优先使用表单中用户输入的值，如果没有则使用从选择器中获取的值
              id_number: partyDetailForm.id_number || selectedParty.value!.id_number || '',
              phone: partyDetailForm.phone || selectedParty.value!.phone || '',
              contact: partyDetailForm.contact || selectedParty.value!.contact || '',
              address: partyDetailForm.address || selectedParty.value!.address || '',
              is_client: partyDetailForm.is_client,
              relationship: partyDetailForm.relationship,
            }

            // 调用API添加关联关系到oa_lawcase_party表
            const response: any = await request.post('/api/lawcase/parties/add', params)
            if (response.code === 0) {
              ElMessage.success('添加当事人成功')
              emit('success')
              handleClose()
            } else {
              ElMessage.error(response.msg || '添加当事人失败')
            }
          }
        } catch (error) {
          ElMessage.error('操作失败')
        } finally {
          loading.value = false
        }
      } else {
        ElMessage.warning('请完善当事人详细信息')
      }
    })
  }

  const handleTabChange = (tabName: string) => {
    console.log('切换到标签页:', tabName)
    // 当切换到客户标签页时，确保联系人列表已加载
    if (
      tabName === 'customer' &&
      localContractInfo.value?.customer_id &&
      customerContacts.value.length === 0
    ) {
      loadCustomerContacts()
    }
    // 当切换到外部当事人标签页时，确保外部当事人列表已加载
    if (tabName === 'external' && externalParties.value.length === 0) {
      loadExternalParties()
    }
  }

  const handleClose = () => {
    dialogVisible.value = false
    // 重置表单和数据
    selectedParty.value = null
    isAddingNewParty.value = false

    // 重置表单数据
    if (partyDetailFormRef.value) {
      partyDetailFormRef.value.resetFields()
    }

    // 重置表单对象
    Object.assign(partyDetailForm, {
      name: '',
      party_type: 1,
      id_number: '',
      phone: '',
      contact: '',
      address: '',
      is_client: 1,
      relationship: 1,
      remark: '',
    })

    // 清空合同信息和联系人数组，确保下次打开不同案件时重新加载
    localContractInfo.value = null
    customerContacts.value = []
    externalParties.value = []
  }

  // 监听对话框显示状态
  watch(dialogVisible, newVal => {
    if (newVal) {
      console.log('对话框打开，尝试加载数据:', {
        contractId: props.contractId,
        caseId: props.caseId,
        hasContractInfo: !!localContractInfo.value,
      })
      // 当对话框打开时，确保数据正确加载
      // 1. 始终加载所有当事人数据
      loadExternalParties()

      // 2. 如果有contractInfo但没有联系人数据，则加载联系人
      if (
        localContractInfo.value &&
        localContractInfo.value.customer_id &&
        customerContacts.value.length === 0
      ) {
        loadCustomerContacts()
      }
      // 3. 如果没有contractInfo但有contractId，则加载合同信息（会自动触发联系人加载）
      else if (
        !localContractInfo.value &&
        props.contractId !== null &&
        props.contractId !== undefined &&
        String(props.contractId).trim() !== ''
      ) {
        loadContractInfo()
      }
      // 4. 不再需要加载已关联当事人（功能已取消）
    }
  })

  // 初始化
  onMounted(() => {
    console.log('传入的props数据:', {
      contractId: props.contractId,
      caseId: props.caseId,
      contractInfo: props.contractInfo,
      contactList: props.contactList,
    })

    // 优先使用传入的contractInfo数据
    if (props.contractInfo) {
      localContractInfo.value = props.contractInfo

      // 如果传入了联系人列表，直接使用
      if (props.contactList) {
        customerContacts.value = props.contactList
      } else if (
        localContractInfo.value?.customer_id &&
        isValidPositiveId(localContractInfo.value.customer_id)
      ) {
        // 否则加载联系人列表
        loadCustomerContacts()
      }
    } else if (
      props.contractId !== null &&
      props.contractId !== undefined &&
      String(props.contractId).trim() !== ''
    ) {
      // 如果没有传入contractInfo但有contractId，则通过API加载
      loadContractInfo()
    }

    // 不再需要加载已关联当事人（功能已取消）
  })
</script>

<style scoped>
  /* 根容器样式优化 */
  .optimized-party-selector {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
  }

  /* 对话框内容区域优化 */
  .dialog-content {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    min-height: 0; /* 确保flex子元素可以正确收缩 */
  }

  /* 合同信息样式 */
  .contract-info {
    margin-bottom: 20px;
    width: 100%;
    box-sizing: border-box;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 8px;
    flex-shrink: 0;
  }

  .contract-card {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 15px;
    width: 100%;
    box-sizing: border-box;
  }

  .contract-header h4 {
    margin: 0 0 15px 0;
    color: #303133;
    font-size: 16px;
  }

  .detail-item {
    margin-bottom: 8px;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
  }

  .detail-item .label {
    font-weight: bold;
    color: #606266;
    min-width: 80px;
    flex-shrink: 0;
  }

  .detail-item .value {
    color: #303133;
    flex: 1;
    word-break: break-word;
    overflow-wrap: break-word;
  }

  /* 提示信息样式 - 高度压缩优化 */
  .tab-alert {
    margin-bottom: 12px;
    padding: 8px 10px;
    border-radius: 4px;
    background-color: #ecf5ff;
    border: 1px solid #d9ecff;
    font-size: 13px;
  }

  /* 当事人选项列表 */
  .party-options {
    display: flex;
    flex-direction: column;
    gap: 8px; /* 减少选项间距 */
    width: 100%;
    box-sizing: border-box;
  }

  .contact-list h5 {
    margin: 5px 0;
    color: #606266;
    font-size: 13px;
    font-weight: normal;
  }

  /* 当事人选项卡片 - 高度压缩优化 */
  .party-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px; /* 减少内边距 */
    border: 1px solid #ebeef5;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    width: 100%;
    box-sizing: border-box;
    flex-wrap: wrap;
  }

  .party-option:hover {
    border-color: #409eff;
    box-shadow: 0 1px 8px 0 rgba(64, 158, 255, 0.1);
  }

  .party-option.selected {
    border-color: #409eff;
    background-color: #ecf5ff;
  }

  .party-info {
    flex: 1;
    min-width: 180px;
  }

  .party-name {
    font-weight: bold;
    font-size: 14px;
    color: #303133;
    margin-bottom: 2px;
    word-break: break-word;
    overflow-wrap: break-word;
    line-height: 1.4;
  }

  .party-type {
    font-size: 12px;
    color: #606266;
    line-height: 1.3;
  }

  .party-phone {
    font-size: 12px;
    color: #909399;
    margin-top: 1px;
    word-break: break-word;
    overflow-wrap: break-word;
    line-height: 1.3;
  }

  /* 当事人元信息 */
  .party-meta {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-shrink: 0;
  }

  /* 外部当事人区域 */
  .external-party-section {
    display: flex;
    flex-direction: column;
    gap: 20px;
    width: 100%;
    box-sizing: border-box;
  }

  /* 新当事人表单 */
  .new-party-form {
    margin-top: 20px;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #f5f7fa;
    width: 100%;
    box-sizing: border-box;
    overflow-x: hidden;
  }

  /* 已关联当事人列表 */
  .related-party-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
    width: 100%;
    box-sizing: border-box;
  }

  .party-role {
    font-size: 13px;
    color: #909399;
    margin-top: 5px;
  }

  /* 无数据提示 */
  .no-related-parties,
  .no-contacts {
    text-align: center;
    padding: 20px 0;
    min-height: 100px;
    width: 100%;
    box-sizing: border-box;
    color: #909399;
  }

  .contact-list {
    display: flex;
    flex-direction: column;
    min-height: 100px;
    width: 100%;
    box-sizing: border-box;
  }

  /* 当事人详情表单 - 高度压缩优化 */
  .party-detail-form {
    margin-top: 15px;
    padding-top: 15px;
    padding-bottom: 15px;
    border-top: 1px solid #ebeef5;
    width: 100%;
    box-sizing: border-box;
    min-height: auto;
    /* 根据内容自适应高度 */
    max-height: none;
  }

  /* 搜索框和分页布局样式 */
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 16px;
  }

  .list-header h5 {
    margin-right: 20px;
    flex-shrink: 0;
    margin-bottom: 0;
  }

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  }

  .search-input {
    width: 300px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .no-party-selected {
    margin-top: 15px;
    padding-top: 15px;
    padding-bottom: 10px;
    border-top: 1px solid #ebeef5;
    text-align: center;
    color: #909399;
    font-size: 13px;
  }

  .loading-container {
    padding: 20px 0;
    text-align: center;
  }

  /* 标签页内容区域优化 */
  .el-tabs__content {
    width: 100%;
    box-sizing: border-box;
    overflow-x: hidden !important;
    overflow: visible;
  }

  .tab-content {
    width: 100%;
    box-sizing: border-box;
    padding: 10px 0;
    overflow-x: hidden;
  }

  /* 标签页内容区域样式 - 根据业务逻辑调整，客户联系人最多不超过3条 */
  .scrollable-tab-content {
    /* 移除固定高度和强制滚动条 */
    overflow: visible; /* 确保内容完全可见 */
  }

  /* 客户及联系人区域特殊样式 */
  .customer-contacts-section {
    /* 针对客户联系人列表的特殊处理，根据业务逻辑最多3条记录 */
    overflow-y: visible;
  }

  /* 外部当事人和已关联当事人区域 */
  .external-parties-section,
  .related-parties-section {
    /* 移除最大高度限制，让内容自然显示 */
    max-height: none;
    overflow-y: auto;
    scrollbar-width: thin;
    scrollbar-color: var(--el-text-color-secondary) var(--el-bg-color);
  }

  /* 为有滚动需求的区域添加滚动条样式 */
  .external-parties-section,
  .related-parties-section {
    scrollbar-width: thin;
    scrollbar-color: #c0c4cc #f0f2f5;
  }

  .external-parties-section::-webkit-scrollbar,
  .related-parties-section::-webkit-scrollbar {
    width: 4px;
    height: 4px;
  }

  .external-parties-section::-webkit-scrollbar-track,
  .related-parties-section::-webkit-scrollbar-track {
    background: #f0f2f5;
    border-radius: 2px;
  }

  .external-parties-section::-webkit-scrollbar-thumb,
  .related-parties-section::-webkit-scrollbar-thumb {
    background-color: #c0c4cc;
    border-radius: 2px;
  }

  .external-parties-section::-webkit-scrollbar-thumb:hover,
  .related-parties-section::-webkit-scrollbar-thumb:hover {
    background-color: #909399;
  }

  /* Element Plus 抽屉样式覆盖 */
  :deep(.el-drawer__body) {
    overflow-x: hidden !important;
    padding-right: 24px;
    padding-left: 24px;
    /* 移除固定高度计算，使用自然高度 */
    min-height: calc(100% - 120px); /* 最小高度，确保在内容较少时也有足够空间 */
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
  }

  /* 确保抽屉容器不会产生水平滚动 */
  :deep(.el-drawer__wrapper) {
    overflow-x: hidden;
  }

  /* 表单内容区域优化 */
  .new-party-form-content,
  .party-detail-form-content {
    width: 100%;
    box-sizing: border-box;
    overflow-x: hidden;
  }

  /* Element Plus 表单样式优化 */
  :deep(.el-form-item) {
    width: 100%;
    box-sizing: border-box;
  }

  :deep(.el-form-item__content) {
    width: 100%;
    box-sizing: border-box;
  }

  /* 确保输入框等表单元素不会超出容器 */
  :deep(.el-input),
  :deep(.el-select),
  :deep(.el-input-number),
  :deep(.el-cascader) {
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
  }

  /* 确保表格不会产生水平滚动 */
  :deep(.el-table) {
    width: 100%;
    overflow-x: hidden;
    box-sizing: border-box;
  }

  /* 响应式设计：在小屏幕上优化布局 */
  @media (max-width: 768px) {
    .detail-item {
      flex-direction: column;
      align-items: flex-start;
    }

    .detail-item .label {
      margin-bottom: 4px;
    }

    .party-option {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }

    .party-meta {
      width: 100%;
      justify-content: flex-end;
    }

    .party-detail-form-content {
      margin-bottom: 20px;
    }
  }
</style>
